package xin.yangshuai.zookeeper011.case1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {

    // 注意：逗号左右不能有空格
    private String connectString = "192.168.145.132:2181,192.168.145.133:2181,192.168.145.134:2181";
    // 2000毫秒
    private int sessionTimeout = 2000;

    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        DistributeClient client = new DistributeClient();
        // 1. 连接zookeeper
        client.getConnect();

        // 2. 监听/servers节点的子节点的增删变化
        // 不用主动调用getServerList方法，创建zookeeper连接的时候，会执行一次监听器的process方法，方法内调用了getServerList方法，达到了监听的效果
        // client.getServerList();

        // 3. 启动业务逻辑（保持运行状态）
        client.business();

    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }



    private void getConnect() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                // 初始化时，会执行一次
                System.out.println(watchedEvent.getPath() + "----------------------------");
                // 由于注册一次，监听一次，如果想持续监听，可重新注册
                try {
                    getServerList();
                } catch (KeeperException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getServerList() throws KeeperException, InterruptedException {
        // 参数watch设置为true，表示使用zkClient创建时的Watcher，并监听当前节点的子节点的增删变化
        List<String> children = zkClient.getChildren("/servers", true);

        List<String> servers = new ArrayList<>();
        for (String child : children) {
            System.out.println(child + "--------------------");

            byte[] data = zkClient.getData("/servers/" + child, false, null);

            servers.add(new String(data));
        }

        System.out.println(servers);
    }
}
